package com.bluetron.supos.apps.exceptions;

import java.sql.SQLException;
import java.util.stream.Collectors;

import javax.validation.ConstraintViolationException;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.server.ResponseStatusException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理参数校验异常
     * 
     * @param e
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public void handleConstraintViolationException(ConstraintViolationException e) {
        log.error("参数校验失败", e);
        String errorMessage = e.getConstraintViolations().stream()
                .map(violation -> violation.getPropertyPath() + ": " + violation.getMessage())
                .collect(Collectors.joining(", "));
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "参数校验失败：" + errorMessage, e);
    }

    /**
     * 处理SQL异常
     * 
     * @param e
     */
    @ExceptionHandler(SQLException.class)
    public void handleSQLException(SQLException e) {
        log.error("数据库操作失败", e);
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "数据库操作失败：" + e.getMessage(), e);
    }

    /**
     * 处理业务异常
     * 
     * @param e
     */
    @ExceptionHandler(AppException.class)
    public void handleAppException(AppException e) {
        log.error("业务异常", e);
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "业务异常：" + e.getMessage(), e);
    }

    /**
     * 处理其他异常
     * 
     * @param e
     */
    @ExceptionHandler(Exception.class)
    public void handleException(Exception e) {
        log.error("系统未知异常", e);
        throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "系统未知异常：" + e.getMessage(), e);
    }
}
